#include "DocParser.h"

using namespace mosqoo::util;

DocParser::DocParser()
{
    //ctor
}

DocParser::~DocParser()
{
    //del map
    delete[] error;
    errorOffset = 0;
}

string DocParser::registerRegex(string regex)
{
    char *tmp;
    itoa(regexPool.size() + 1, tmp, 10);
    string name = "REGEX_";
    name.append(tmp);
    regexPool.insert(map<string, pcre*>::value_type(name,
        pcre_compile(regex.c_str(), PCRE_UTF8, &error, &errorOffset, NULL)));
    return name;
}

string DocParser::registerRegex(string regex, string key)
{
    if (regexPool.find(key) == regexPool.end())
    {
        regexPool.insert(map<string, pcre*>::value_type(key,
            pcre_compile(regex.c_str(), PCRE_UTF8, &error, &errorOffset, NULL)));
    }
    else
    {
        // TODO throw exception name already exist
    }
    return key;
}

vector<string> DocParser::search(string key, string content)
{
    int ovector[OVECCOUNT];
    int rc;
    vector<string> result;
    rc = pcre_exec((pcre*)regexPool[key], NULL, content.c_str(), content.length(), 0, 0, ovector, OVECCOUNT);

    if (!(rc < PCRE_ERROR_NOMATCH))
    {
        for (int i = 0; i < rc; i++)
        {
            result.insert(result.end(),content.substr(ovector[i<<1], ovector[(i<<1)+1]-ovector[i<<1]));
        }
    }
    return result;
}
